<?php

class Photo_model extends MY_Model {

    public function __construct() {
	parent::__construct();

	$this->table = 'jd_photo';
    }

    public function records($limit = 0, $offset = 0, $conditions = array()) {
	$this->db->from($this->table);

	if (!empty($conditions)) {
	    foreach ($conditions as $condition) {
		$this->db->where($condition[0], $condition[1]);
	    }
	}

	if ($limit) {
	    $this->db->limit($limit, $offset);
	}

	$this->db->order_by('order', 'desc');

	$query = $this->db->get();

	return $query->result();
    }

    public function order($id, $new_order) {
	$photo = $this->find($id);

	if ($photo->order > $new_order) {
	    $end_order = $photo->order - 1;
	    $sql = "update `{$this->table}`
            set `order`=`order`+1
            where `order`>='{$new_order}'
            and `order`<='{$end_order}'
	    and `album`={$photo->album};";
	} else {
	    $start_order = $photo->order + 1;
	    $sql = "update `{$this->table}`
            set `order`=`order`-1
            where `order`>='{$start_order}'
            and `order`<='{$new_order}'
	    and `album`={$photo->album};";
	}

	$this->db->query($sql);

	return $this->update($id, array('order' => $new_order));
    }

}
